package com.jn.erp.wechat.student.handler;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.json.WxMaGsonBuilder;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.ImmutableMap;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * <pre>
 *  小程序信息相关
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/9/25 14:05
 */
//@AllArgsConstructor
@Component
public class StudentMpInfoHandler {

    private final WxMaService wxMaService;

    @Autowired
    public StudentMpInfoHandler(@Qualifier("parentWxMaService") WxMaService wxMaService){
        this.wxMaService = wxMaService;
    }

    //该接口用于将code换取用户手机号。 说明，每个code只能使用一次，code的有效期为5min。
    public JSONObject getPhoneNumber(String code) {
        try {
            Map<String, String> params = ImmutableMap.of("code", code);
            String post = wxMaService.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber", WxMaGsonBuilder.create().toJson(params));
            JSONObject info = JSONObject.parseObject(post);
            WxMaConfigHolder.remove();//清理ThreadLocal
            return info;
        } catch (WxErrorException e) {
            System.out.println(e.getError());
            return null;
        }catch (Exception e){
            System.out.println("获取wx返回格式有误");
            return null;
        }

    }
    //oHFcD6-BBcUKxFx-2k0Vb6ffDGWs

}
